<template>
  <div class="supplier-container">
    <!-- 页面标题和操作按钮 -->
    <el-page-header @back="handleBack" content="供应商管理"></el-page-header>

    <!-- 搜索和添加区域 -->
    <el-row :gutter="20" class="search-bar">
      <el-col :span="16">
        <el-input
            v-model="searchKeyword"
            placeholder="请输入供应商名称、联系人或电话搜索"
            clearable
            @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="8" class="text-right">
        <el-button type="success" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          <span>添加供应商</span>
        </el-button>
      </el-col>
    </el-row>

    <!-- 供应商列表 -->
    <el-table
        :data="supplierList"
        border
        stripe
        style="width: 100%; margin-top: 20px"
        v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="80"></el-table-column>
      <el-table-column prop="name" label="供应商名称" min-width="150"></el-table-column>
      <el-table-column prop="contact" label="联系人" min-width="100"></el-table-column>
      <el-table-column prop="phone" label="联系电话" min-width="120"></el-table-column>
      <el-table-column prop="address" label="地址" min-width="200"></el-table-column>
      <el-table-column label="状态" min-width="100">
        <template #default="scope">
          <el-tag
              :type="scope.row.status === 1 ? 'success' : 'warning'"
          >
            {{ scope.row.status === 1 ? '正常' : '已冻结' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200" fixed="right">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleFreeze(scope.row)"
          >
            {{ scope.row.status === 1 ? '冻结' : '解冻' }}
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="total > 0"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        style="margin-top: 15px; text-align: right"
        @current-change="handlePageChange"
    ></el-pagination>

    <!-- 添加/编辑供应商弹窗 -->
    <el-dialog
        :title="isEdit ? '编辑供应商' : '添加供应商'"
        v-model="showDialog"
        :width="dialogWidth"
        @opened="onDialogOpened"
    >
      <el-form
          :model="formData"
          :rules="formRules"
          ref="supplierForm"
          label-width="120px"
      >
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入供应商名称"></el-input>
        </el-form-item>

        <el-form-item label="联系人" prop="contact">
          <el-input v-model="formData.contact" placeholder="请输入联系人"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input
              v-model="formData.address"
              placeholder="请输入地址"
              type="textarea"
              :rows="3"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" value="1"></el-option>
            <el-option label="冻结" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmSubmit"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllSuppliers,
  addSupplier,
  updateSupplier,
  freezeSupplier,
  deleteSupplier,
  searchSuppliers,
  getSupplierById
} from '../api/supplier';
import { Plus } from '@element-plus/icons-vue';

export default {
  components: {
    Plus
  },
  data() {
    // 表单验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入联系电话'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号格式'));
      } else {
        callback();
      }
    };

    return {
      // 表格数据
      supplierList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,

      // 搜索条件
      searchKeyword: '',

      // 弹窗控制
      showDialog: false,
      isEdit: false,
      dialogWidth: '500px',

      // 表单数据
      formData: {
        supplierId: null,
        name: '',
        contact: '',
        phone: '',
        address: '',
        status: 1
      },

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        address: [
          { required: false }
        ]
      }
    };
  },

  mounted() {
    this.loadSupplierList();
  },

  methods: {
    // 返回上一页
    handleBack() {
      this.$router.back();
    },

    // 加载供应商列表
    async loadSupplierList() {
      this.loading = true;
      try {
        let {data:data} = await getAllSuppliers();
        if (data.code === 200) {
          this.supplierList = data.data;
          this.total = data.data.length;
        } else {
          this.$message.error(data.msg || '获取供应商列表失败');
        }
      } catch (error) {
        this.$message.error('获取供应商列表失败');
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    // 搜索供应商
    async handleSearch() {
      this.loading = true;
      try {
        let {data:data} = await searchSuppliers(this.searchKeyword);
        if (data.code === 200) {
          this.supplierList = data.data;
          this.total = data.data.length;
          this.currentPage = 1;
        } else {
          this.$message.error(res.msg || '搜索失败');
        }
      } catch (error) {
        this.$message.error('搜索失败');
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    // 分页变化
    handlePageChange(page) {
      this.currentPage = page;
    },

    // 打开添加弹窗
    openAddDialog() {
      this.isEdit = false;
      this.formData = {
        supplierId: null,
        name: '',
        regionId: null,
        contact: '',
        phone: '',
        address: '',
        status: 1,

      };
      this.showDialog = true;
    },

    // 弹窗打开后的回调 - 仅清除表单验证状态，不再重置数据
    onDialogOpened() {
      if (this.$refs.supplierForm) {
        this.$refs.supplierForm.clearValidate();
      }
    },
// 处理编辑
    async handleEdit(supplier) {
      this.isEdit = true;
      try {
        let { data: resData } = await getSupplierById(supplier.supplierId);
        // console.log(resData);
        if (resData.code === 200) {
          // 先组装表单数据
          this.formData = {
            supplierId: resData.data.supplierId,
            name: resData.data.name,
            contact: resData.data.contact,
            phone: resData.data.phone,
            address: resData.data.address,
            status: resData.data.status
          };
          // console.log(this.formData);
          // 再打开弹窗
          this.showDialog = true;
          // 弹窗打开后，清除表单验证状态（而不是重置表单数据）
          await this.$nextTick(() => {
            if (this.$refs.supplierForm) {
              this.$refs.supplierForm.clearValidate();
            }
          });
        } else {
          this.$message.error(resData.msg || '获取供应商详情失败');
        }
      } catch (error) {
        this.$message.error('获取供应商详情失败');
        console.error(error);
      }
    },
    // 处理冻结/解冻
    async handleFreeze(supplier) {
      const newStatus = supplier.status === 1 ? 0 : 1;
      const actionText = newStatus === 0 ? '冻结' : '解冻';

      this.$confirm(`确定要${actionText}供应商"${supplier.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          let {data:data} = await freezeSupplier(supplier.supplierId, newStatus);
          if (data.code === 2005) {
            this.$message.success(`${actionText}成功`);
            await this.loadSupplierList();
          } else {
            this.$message.error(data.msg || `${actionText}失败`);
          }
        } catch (error) {
          this.$message.error(`${actionText}失败`);
          console.error(error);
        }
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },

    // 处理删除
    async handleDelete(supplier) {
      this.$confirm(`确定要删除供应商"${supplier.name}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        try {
          let {data:data} = await deleteSupplier(supplier.supplierId);
          if (data.code === 2007) {
            this.$message.success('删除成功');
            await this.loadSupplierList();
          } else {
            this.$message.error(data.msg || '删除失败');
          }
        } catch (error) {
          this.$message.error('删除失败');
          console.error(error);
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 确认提交（添加/编辑）
    async confirmSubmit() {
      await this.$refs.supplierForm.validate(async (valid) => {
        if (valid) {
          try {

            if (this.isEdit) {
              let {data:data} = await updateSupplier(this.formData);
              if (data.code === 200) {
                this.$message.success('修改成功');
              } else {
                this.$message.error(data.msg || '修改失败');
                return;
              }
            } else {
              let {data:data} = await addSupplier(this.formData);
              if (data.code === 200) {
                this.$message.success('添加成功');
              } else {
                this.$message.error(data.msg || '添加失败');
                return;
              }
            }

            this.showDialog = false;
            this.loadSupplierList();
          } catch (error) {
            this.$message.error(this.isEdit ? '修改失败' : '添加失败');
            console.error(error);
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.supplier-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

.search-bar {
  margin-top: 20px;
}

::v-deep .el-form-item__error {
  padding-top: 5px;
}
</style>